package com.utopia.keyvalue.store.impl.disk;

import java.nio.ByteBuffer;

import com.utopia.keyvalue.utils.ByteSerializer;

/**
 * @author yanjiaqiang
 * @date 2011-3-17
 * @version $Id: DataEntry.java 5 2011-03-22 09:23:42Z JiaqiangYan@gmail.com $
 */
public class DataEntry implements ByteSerializer {

	public static byte DELETED = 1;
	public static byte UNDELETED = 0;
	/**
	 * 是否已删除
	 */
	private boolean isDeleted;

	/**
	 * 数据长度
	 */
	private int length;

	/**
	 * 实际的数据
	 */
	private byte[] data;

	public DataEntry() {
		super();

	}

	public DataEntry(byte[] data) {
		super();
		this.data = data;
		this.length = data.length;
	}

	public boolean isDeleted() {
		return isDeleted;
	}

	public void setDeleted(boolean isDeleted) {
		this.isDeleted = isDeleted;
	}

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

	public byte[] getData() {
		return data;
	}

	public void setData(byte[] data) {
		this.data = data;
	}

	@Override
	public byte[] toBytes() {
		ByteBuffer buf = ByteBuffer.allocate(5 + data.length);
		buf.put(isDeleted ? DELETED : UNDELETED);
		buf.putInt(length);
		buf.put(data);
		return buf.array();
	}

	@Override
	public void fromBytes(byte[] bs) {
		ByteBuffer buf = ByteBuffer.wrap(bs);
		this.isDeleted = (buf.get() == DELETED ? true : false);
		this.length = buf.getInt();
		this.data = new byte[length];
		buf.get(data);
	}

}
